import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { loadEnv } from 'vite'
import styleImport, { VantResolve } from 'vite-plugin-style-import';
import { resolve } from 'path'
import postCssPxToRem from 'postcss-pxtorem'
export default ({ mode }) => {
  console.log(loadEnv(mode, process.cwd()).VITE_NODE_ENV)
  return defineConfig({
    plugins: [
      vue(),
      styleImport({
        resolves: [VantResolve()],
        libs: [
          {
            libraryName: 'vant',
            esModule: true,
            // resolveStyle: (name) => `../es/${name}/index.css`,
            resolveStyle: (name) => {
              if (name=== 'show-toast' || name === 'show-loading-toast' || name=== 'close-toast') {
                return `../es/toast/index.css`
              } else if (name=== 'show-dialog') {
                return `../es/dialog/index.css`
              } else {
                return `../es/${name}/index.css`
              }
            },
          },
        ],
      }),
    ],

    // base:loadEnv(mode, process.cwd()).VITE_APP_NAME,
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src')
      },
      extensions: ['.js', '.vue', '.ts'],

    },
    build: {
      outDir: loadEnv(mode, process.cwd()).VITE_APP_OUTPUT_DIR,
      minify: 'terser',
      // 进行压缩计算
      brotliSize: false,
      sourcemap: false,
      terserOptions: {
        compress: {
          // 打包自动删除console
          // drop_console: true,
          // drop_debugger: true
        },
        keep_classnames: true,
      },
      chunkSizeWarningLimit: 1600
      // rollupOptions: {
      //   external: ['vant']
      // }
    },
    css: {
      postcss: {
        plugins: [
          postCssPxToRem({
            rootValue: 37.5,
            selectorBlackList: [".van-"],// 过滤掉开头是 .no-rem 的class，或者包含 .van- 的clas
            propList: ['*'],
            exclude: ['node_modules']
          })
        ]
      },
      //css预处理
      preprocessorOptions: {
        scss: {
          /*
          引入var.scss全局预定义变量，
          如果引入多个文件，
          可以使用
          '@import "@/assets/scss/globalVariable1.scss";@import "@/assets/scss/globalVariable2.scss";'
          这种格式
           */
          additionalData: '@import "@/style/common.scss";'
        }
      }
    },

    server: {
      port: 3000, // 设置服务启动端口号
      open: false, // 设置服务启动时是否自动打开浏览器
      // host: "127.0.0.1",
      host: "0.0.0.0",
      force: false,
      proxy: {
        '/api': {
          target: loadEnv(mode, process.cwd()).VITE_CURRENT_API,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        },
      },

    }
  })
}